<template>
    <div class="user-modal">
        <a-modal
            v-model:visible="modalVisible"
            :title="props.modalTitle"
            dialogClass="modal"
            :footer="null"
            :maskClosable="false"
            @cancel="modalCancel"
        >
            <div class="modal-form">
                <a-form
                    :model="modalContentForm"
                    name="modal-user-form"
                    :labelCol="{span: 4}"
                >
                    <a-form-item label="用户名">
                        <a-input v-model:value="modalContentForm.username" :disabled="modalContentForm.id"/>
                    </a-form-item>
                    <a-form-item label="密码" v-if="!modalContentForm.id">
                        <a-input-password v-model:value="modalContentForm.password"/>
                    </a-form-item>
                    <a-form-item label="昵称">
                        <a-input v-model:value="modalContentForm.nickName"/>
                    </a-form-item>
                    <a-form-item label="头像">
                        <a-upload
                            v-model:file-list="fileList"
                            name="file"
                            list-type="picture-card"
                            class="avatar-uploader"
                            :show-upload-list="false"
                            :maxCount="1"
                            action="https://upload-z2.qiniup.com"
                            :data="uploadData"
                            :before-upload="beforeUpload"
                            @change="handleChange"
                        >
                            <img v-if="modalContentForm.avatar" :src="modalContentForm.avatar" alt="avatar" />
                            <div v-else>
                                <loading-outlined v-if="loading"></loading-outlined>
                                <plus-outlined v-else></plus-outlined>
                                <div class="ant-upload-text">Upload</div>
                            </div>
                        </a-upload>
                    </a-form-item>
                    <a-form-item label="角色">
                        <a-select
                            v-model:value="modalContentForm.roles"
                            mode="multiple"
                            placeholder="请选择要绑定的角色"
                            style="width: 100%"
                            :options="selectRoleDataSource"
                            :fieldNames="{
                                label: 'roleName',
                                value: 'id',
                            }"
                        >

                        </a-select>
                    </a-form-item>
                    <a-form-item label="邮箱">
                        <a-input v-model:value="modalContentForm.email"/>
                    </a-form-item>
                    <a-form-item label="手机号">
                        <a-input v-model:value="modalContentForm.mobile"/>
                    </a-form-item>
                    <a-form-item label="是否可用">
                        <a-switch v-model:checked="modalContentForm.available">
                            <template #checkedChildren><check-outlined /></template>
                            <template #unCheckedChildren><close-outlined /></template>
                        </a-switch>
                    </a-form-item>
                    <div class="modal-form-btn">
                        <div>
                            <a-button type="primary" block	:shape="'round'" @click="submitForm">提交</a-button>
                        </div>
                    </div>
                </a-form>
            </div>
        </a-modal>
    </div>
</template>

<script setup lang="ts">
import {reactive, ref} from "vue";
import {UserModalForm} from "@v/home/system/user/types/types";
import {message, UploadChangeParam, UploadProps} from "ant-design-vue";
import {QINIU_OSS_CONFIG} from "@/configs/constants";
import {getOssUploadToken} from "@/apis/third-apis";
import {ADD_USER, QUERY_BY_USER_ID, UPDATE_USER, USER_BIND_ROLES} from "@/apis/user-apis";
import {RoleVO} from "@/apis/types";
import {ROLE_LIST} from "@/apis/role-apis";

const props = defineProps<{
    modalTitle: string,
}>();

const emits = defineEmits<{
    (e: "refreshData"): void
}>()

const modalVisible = ref<boolean>();
const isUpdate = ref<boolean>();
const modalContentForm = ref<UserModalForm>({
    available: true,
    avatar: "",
    email: "",
    mobile: "",
    nickName: "",
    username: "",
    id: null,
    password: null,
    roles: []
});

const fileList = ref([]);
const loading = ref<boolean>(false);

const uploadData = ref<Record<string, any>>({
    token: "",
    key: ""
});

/**
 * 渲染表单数据
 *
 * @param userId 用户id
 */
const renderFormData = (userId:string) => {
    console.log("是修改喔", isUpdate.value, userId)
    // 查找要修改的用户信息
    QUERY_BY_USER_ID(userId).then(res => {
        console.log("update", res);
        modalContentForm.value.id = res.data.id;
        modalContentForm.value.avatar = res.data.avatar;
        modalContentForm.value.available = res.data.available;
        modalContentForm.value.email = res.data.email;
        modalContentForm.value.mobile = res.data.mobile;
        modalContentForm.value.username = res.data.username;
        modalContentForm.value.nickName = res.data.nickName;
        modalContentForm.value.roles = [];
        res.data.roles.map((val) => modalContentForm.value.roles.push(val.id));
    })
}
/**
 * 模态框关闭事件
 */
const modalCancel = () => {
    // 清空输入框
    modalContentForm.value = {
        available: true,
        avatar: "",
        email: "",
        mobile: "",
        nickName: "",
        username: "",
        id: null,
        password: null,
        roles:[]
    }
}

const selectRoleDataSource = ref<Array<RoleVO>>();

const handleChange = (info: UploadChangeParam) => {
    if (info.file.status === 'uploading') {
        loading.value = true;
        return;
    }
    if (info.file.status === 'done') {
        modalContentForm.value.avatar = QINIU_OSS_CONFIG.domain + uploadData.value.key;
    }
    if (info.file.status === 'error') {
        loading.value = false;
        message.error('上传失败...');
    }
};


const beforeUpload: UploadProps['beforeUpload'] = file => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG file!');
        return false;
    }
    const isLt2M = file.size / 1024 / 1024 <= 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
        return false;
    }
    return getOssUploadToken(file.name, QINIU_OSS_CONFIG.avatarDir).then(res => {
        uploadData.value = res.data;
        return Promise.resolve()
    });
}

const submitForm = () => {
    new Promise((resolve, reject) => {
        if (modalContentForm.value.id){
            UPDATE_USER(modalContentForm.value).then(res => {
                message.success("修改成功")
                resolve(res)
            }).catch( err => {
                message.error("修改失败")
                reject(err)
            })
        }else{
            ADD_USER(modalContentForm.value).then(res => {
                message.success("添加成功")
                console.log("添加成功", res)
                resolve(res)
            }).catch( err => {
                message.error("添加失败")
                reject(err)
            })
        }
    }).then((res:any) => {
        let userId = modalContentForm.value.id ?? res.data;
        let roleIds = modalContentForm.value.roles;
        USER_BIND_ROLES(userId, roleIds).then(res => {
            return Promise.resolve(res)
        })
    }).then( () => {
        modalVisible.value = false;
        modalCancel()
        emits("refreshData")
    })
}

const openModal = (update?: boolean) => {
    modalVisible.value = true;
    isUpdate.value = update ?? false;
    ROLE_LIST().then(res => {
        selectRoleDataSource.value = res.data;
        console.log("selectRoleDataSource", selectRoleDataSource);
    })
}

defineExpose({
    renderFormData,
    openModal
})
</script>

<style scoped lang="less">
.modal-form-btn{
    width: 100%;
    display: flex;
    justify-content: center;

    div{
        width: 100%;
    }
}

.avatar-uploader {
    img{
        width: 90%;
        height: 90%;
    }
}
</style>
